package com.rymcu.forest.util;

import com.rymcu.forest.auth.JwtConstants;
import com.rymcu.forest.dto.TokenUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT 工具类
 *
 * @author ronger
 */
@Slf4j
@Component
public class JwtUtils {

    private static final SecretKey KEY = Keys.hmacShaKeyFor(JwtConstants.JWT_SECRET.getBytes(StandardCharsets.UTF_8));

    /**
     * 生成JWT token
     *
     * @param tokenUser 用户信息
     * @return JWT token
     */
    public String generateToken(TokenUser tokenUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", tokenUser.getIdUser());
        claims.put("nickname", tokenUser.getNickname());
        claims.put("avatarUrl", tokenUser.getAvatarUrl());
        if (tokenUser.getScope() != null) {
            claims.put("scope", tokenUser.getScope());
        }

        Date now = new Date();
        Date expiration = new Date(now.getTime() + JwtConstants.TOKEN_EXPIRES_HOUR * 60 * 60 * 1000);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(tokenUser.getAccount())
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(KEY)
                .compact();
    }

    /**
     * 解析JWT token
     *
     * @param token JWT token
     * @return Claims
     */
    public Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 验证token是否有效
     *
     * @param token JWT token
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            log.error("JWT token validation failed: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 从token中获取用户名
     *
     * @param token JWT token
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 从token中获取用户ID
     *
     * @param token JWT token
     * @return 用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        Object userIdObj = claims.get("userId");
        if (userIdObj instanceof Integer) {
            return ((Integer) userIdObj).longValue();
        } else if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        } else if (userIdObj instanceof String) {
            return Long.parseLong((String) userIdObj);
        }
        return null;
    }

    /**
     * 检查token是否过期
     *
     * @param token JWT token
     * @return 是否过期
     */
    public boolean isTokenExpired(String token) {
        try {
            Claims claims = parseToken(token);
            return claims.getExpiration().before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 刷新token
     *
     * @param token 原始token
     * @param tokenUser 用户信息
     * @return 新token
     */
    public String refreshToken(String token, TokenUser tokenUser) {
        // 验证原token
        if (!validateToken(token)) {
            throw new IllegalArgumentException("Invalid token");
        }

        // 生成新token
        return generateToken(tokenUser);
    }
}